import axios, { AxiosInstance } from 'axios';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { Session } from '/@/utils/storage';
import qs from 'qs';
import { tansParams, blobValidate } from '/@/utils/angis';
import { saveAs } from 'file-saver';

let downloadLoadingInstance: any;
// 配置新建一个 axios 实例
const service: AxiosInstance = axios.create({
	baseURL: import.meta.env.VITE_API_URL,
	timeout: 50000,
	headers: { 'Content-Type': 'application/json;charset=utf-8' },
	paramsSerializer: {
		serialize(params) {
			return qs.stringify(params, { allowDots: true });
		},
	},
});

// 添加请求拦截器
service.interceptors.request.use(
	(config) => {
		// 在发送请求之前做些什么 token
		if (Session.get('token')) {
			config.headers!['basesys-auth'] = `${Session.get('token')}`;
		}
		return config;
	},
	(error) => {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	(response) => {
		// 对响应数据做点什么
		const res = response.data;
		if (res.code && res.code !== 1) {
			// `token` 过期或者账号已在别处登录
			if (res.code === 401 || res.code === 4001 || res.code === 2000) {
				ElMessageBox.alert('你已被登出，请重新登录', '提示', {}).then(() => {
					Session.clear(); // 清除浏览器全部临时缓存
					window.location.href = '/'; // 去登录页
				});
			}
			return response.data;
		} else if (!res.code && response.status != 200) {
			ElMessageBox.alert(res.msg, '提示', {});
			throw new Error(res.msg);
		} else if (!res.code && response.status == 200) {
			return response;
		} else {
			return response.data;
		}
	},
	(error) => {
		// 对响应错误做点什么
		if (error.message.indexOf('timeout') != -1) {
			ElMessage.error('网络超时');
		} else if (error.message == 'Network Error') {
			ElMessage.error('网络连接错误');
		} else {
			if (error.response.data) ElMessage.error(error.response.statusText);
			else ElMessage.error('接口路径找不到');
		}
		return Promise.reject(error);
	}
);

export function download(url: string, params: object, filename: string, config: object) {
	downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });
	return service
		.post(url, params, {
			transformRequest: [
				(params) => {
					return tansParams(params);
				},
			],
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			responseType: 'blob',
			...config,
		})
		.then(async (data) => {
			if (!filename) {
				filename = decodeURIComponent(data.headers["content-disposition"].split("=")[1])
				filename = filename.replace(/"/g, '')
			}
			const isBlob = blobValidate(data);
			if (isBlob) {
				const blob = new Blob([data.data]);
				saveAs(blob, filename);
			} else {
				const resText = await data.text();
				const rspObj = JSON.parse(resText);
				const errMsg = rspObj.msg;
				ElMessage.error(errMsg);
			}
			downloadLoadingInstance.close();
		})
		.catch((r) => {
			ElMessage.error('下载文件出现错误，请联系管理员！');
			downloadLoadingInstance.close();
		});
}

// 导出 axios 实例
export default service;
